package com.homework.filter;

import homework.facade.dto.IpDTO;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.net.URI;
import java.util.Date;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Component
public class BrushProofIPGatewayFilter implements GlobalFilter, Ordered {

    public static final Map<String,IpDTO> ipMap = new ConcurrentHashMap<>();

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        URI uri = request.getURI();
        String hostName = request.getRemoteAddress().getHostString();
        String path = uri.getPath();
        if (!path.contains("api/user/register")) {
            return chain.filter(exchange);
        }
        IpDTO ipDTO = ipMap.get(hostName);
        if (ObjectUtils.isEmpty(ipDTO)) {
            long time = new Date().getTime();
            time += (1000 * 60);
            ipDTO = new IpDTO();
            ipDTO.setIp(hostName);
            ipDTO.setSum(1);
            ipDTO.setDate(new Date(time));
            ipMap.put(hostName,ipDTO);
            return chain.filter(exchange);
        }
        if (ipDTO.getDate().before(new Date())) {
            long time = new Date().getTime();
            time += (1000 * 60);
            ipDTO = new IpDTO();
            ipDTO.setIp(hostName);
            ipDTO.setSum(1);
            ipDTO.setDate(new Date(time));
            ipMap.put(hostName,ipDTO);
            return chain.filter(exchange);
        }
        if (ipDTO.getSum() < 2) {
            Integer sum = ipDTO.getSum();
            sum += 1;
            ipDTO.setSum(sum);
        }
        String data = "您频繁进⾏注册，请求已被拒绝";
        DataBuffer wrap = response.bufferFactory().wrap(data.getBytes());
        return response.writeWith(Mono.just(wrap));
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
